#include "SoundEngine.h"


vector<Mix_Music*> SoundEngine::m_sounds;
map<string, int> SoundEngine::NameToIDMap;
unsigned int SoundEngine::m_currentlyPlaying = 0;

SoundEngine::SoundEngine()
{
}

SoundEngine::~SoundEngine()
{
}

SoundEngine* SoundEngine::Instance()
{
	static SoundEngine instance;
	return &instance;
}

void SoundEngine::Play(string name)
{
	if(!DataLoader->IsPlayMusicOn())
		return;

	if(m_sounds.size() > 0)
	{
		Mix_PlayMusic(m_sounds[NameToIDMap[name]], -1);
		m_currentlyPlaying = NameToIDMap[name];
	}
}

void SoundEngine::Update()
{
	if(!DataLoader->IsPlayMusicOn())
		return;

	if(Mix_PlayingMusic() == 0) // If music is currently not playing
	{
		++m_currentlyPlaying;
		if(m_currentlyPlaying > (m_sounds.size() - 1))
			m_currentlyPlaying = 0;

		Mix_PlayMusic(m_sounds[m_currentlyPlaying], 1);
	}
}

void SoundEngine::Pause()
{
	if(!DataLoader->IsPlayMusicOn())
		return;

	Mix_PauseMusic();
}
void SoundEngine::Resume()
{
	if(!DataLoader->IsPlayMusicOn())
		return;

	Mix_ResumeMusic();
}
void SoundEngine::StopPlaying()
{
	if(!DataLoader->IsPlayMusicOn())
		return;

	Mix_HaltMusic();
}

void SoundEngine::LoadSound(string name, string filename)
{
	if(!DataLoader->IsPlayMusicOn())
		return;

	Mix_Music* sound = Mix_LoadMUS(filename.c_str());
	assert("Invalid song loaded" && sound);

	m_sounds.push_back(sound);
	NameToIDMap.insert(std::pair<string, int>(name, NameToIDMap.size()));
}

void SoundEngine::Init()
{	
	if(!DataLoader->IsPlayMusicOn())
		return;

	Lua->RunScript("Scripts\\Sounds.lua");
}

void SoundEngine::CleanUp()
{
	if(!DataLoader->IsPlayMusicOn())
		return;

	for(unsigned int i = 0; i < m_sounds.size(); ++i)
	{
		Mix_FreeMusic(m_sounds[i]);
		m_sounds[i] = 0;
	}
}

